import {HTTP} from '../utils/http.js'

class ClassicModel extends HTTP{
  /**
   * 获取最新一期的期刊
   */
  getLatest(sCallBack){
    this.request({
      url:'classic/latest',
      success:(res)=>{
        sCallBack(res);
        //缓存最新的期刊index
        this._setLatestIndex(res.index);
        //数据存入缓存
        let key = this._getKey(res.index);
        wx.setStorageSync(key , res);
      }
    });
  }

  /**
   * 上一期
   */
  getPrevious(index,sCallBack){
    this.getClassic(index , "previous" ,sCallBack);
  }
  /**
   * 下一期
   */
  getNext(index, sCallBack) {
    this.getClassic(index , "next" ,sCallBack);
  }

  /**
   * 获取期刊数据
   * @param {0} index 当前期刊数
   * @param {1} previousOrNext 上一期或下一期操作
   * @param {2} sCallBack 回调函数
   */
  getClassic(index , previousOrNext , sCallBack){
    let key = previousOrNext=="next"?this._getKey(index+1):this._getKey(index-1);
    let classic = wx.getStorageSync(key);
    if(!classic){//缓存没有数据
      this.request({
        url: `classic/${index}/${previousOrNext}`,
        success: (res) => {
          sCallBack(res);
          //存入缓存
          wx.setStorageSync(this._getKey(res.index) , res);
        }
      });
    }else{
      sCallBack(classic);
    }
  }

  getMyFavor(success){
    const params = {
      url: 'classic/favor',
      success: success
    }
    this.request(params);
  }

  /**
   * 判断是否为最新期刊
   * @param {0} index 期刊数
   */
  isLatest(index){
    let latestIndex = this._getLatestIndex();
    return index==latestIndex;
  }
  /**
   * 判断是否为第一期期刊
   * @param {0} index 期刊数
   */
  isFirst(index){
    return index==1;
  }

  /**
   * 在缓存中存放最新一期的期数
   * @param {0} index 期数
   */
  _setLatestIndex(index){
    wx.setStorageSync("latest", index);
  }

  /**
   * 获取最新的期刊数
   */
  _getLatestIndex(){
    return wx.getStorageSync("latest");
  }

  /**
   * 获取缓存的索引
   * @param {0} index期刊期数 
   */
  _getKey(index){
    return "classic-"+index;
  }

}
export {ClassicModel}